package middlewareorid.ui;

import middlewareorid.engine.BlogsoridEngine;
import middlewareorid.engine.Config;
import middlewareorid.engine.ConfigAccess;
import superwaba.ext.xplat.ui.MultiEdit;
import waba.fx.Color;
import waba.fx.Rect;
import waba.io.Catalog;
import waba.ui.Button;
import waba.ui.ComboBox;
import waba.ui.Container;
import waba.ui.ControlEvent;
import waba.ui.Edit;
import waba.ui.Event;
import waba.ui.Label;
import waba.ui.MessageBox;

public class AddBlogWindow extends Container {
	Edit edTtl;
	MultiEdit edSel;
	Label info = new Label("");
	ComboBox cbCategory = new ComboBox();
	Catalog c;
	int paramLenth = 50;
	Button btSubmit = new Button("  Submit  "); 
	ConfigAccess cf = new ConfigAccess();

	public AddBlogWindow(Rect rect) {
		setRect(rect);		
		
		info.setText("  Add New Items  ");
		info.setBackForeColors(Color.BLACK, Color.WHITE);
		add(info, LEFT, TOP);
		
		// Title 
		info = new Label("Item Title");
		add(info, LEFT + 5, AFTER + 5);
		edTtl = new Edit();
		add(edTtl);
		edTtl.setRect(LEFT + 5, AFTER + 3, getClientRect().width-10, PREFERRED);
		
		// Category 
		info = new Label("Item Category");
		add(info, LEFT + 5, AFTER + 3);		
		add(cbCategory);
		cbCategory.setRect(LEFT + 5, AFTER + 3, getClientRect().width-10, PREFERRED);
		listCategory();

		// Information 
		info = new Label("Item Information");
		add(info, LEFT + 5, AFTER + 3);
		edSel = new MultiEdit(3, 0);
		add(edSel);
		edSel.setRect(LEFT + 5, AFTER + 3, rect.width-10, PREFERRED);
		edSel.setDrawDots(false);		

		add(btSubmit, LEFT + 5, AFTER + 5);
	}

	private void listCategory() {
		c = new Catalog("djokdja_category.Crtr.Type",Catalog.READ_ONLY);
		for (int j = 0; j < c.getRecordCount(); j++) {
			byte b[] = new byte[paramLenth];
			c.setRecordPos(j);
			c.readBytes(b, 0, paramLenth);
			String cat = new String(b);
			cbCategory.insert(cat.trim(), j);
		}
		c.close();
	}

	public void onEvent(Event event) {
		switch (event.type) {
		case ControlEvent.PRESSED:
			if (event.target == btSubmit) {
				String cat = cbCategory.getSelectedItem().toString();
				int start = cat.indexOf("++");
				cat = cat.substring(0, start);
				int i = BlogsoridEngine.addBlogs(edTtl.getText(), cat, edSel.getText(), cf.getConfigFromCatalog(cf.APP_USER), cf.getConfigFromCatalog(cf.APP_PASSWORD));
				if (i < 0) {
					new MessageBox("Error", "Send new item failed !!, please try again ...");
				}
			}
			break;
		}
	}
	
	public void setStyle(int style) {
		setBackColor(Config.background[style]);
	}
}
